package cn.tedu._03vehice.base.interceptors;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class RateLimitInterceptor implements HandlerInterceptor {
    private static final int MAX_REQUEST_PER_MINUTE = 3;
    private static final int WINDOW_SIZE_SECONDS = 60;

    //{"192.168.1.11": 2, "192.168.1.12": 3, "192.168.1.12": 1}
    private final ConcurrentHashMap<String, Integer> clientCount = new ConcurrentHashMap<>();

    //{"192.168.1.11": "2025-02-15 00:00:00", "192.168.1.12": "2025-02-15 11:11:11"}
    private final ConcurrentHashMap<String, LocalDateTime> clientTimes = new ConcurrentHashMap<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("kaishi");
        String addr = request.getRemoteAddr();
        LocalDateTime lastTime = clientTimes.get(addr);
        if(lastTime == null || lastTime.isAfter(lastTime.plusSeconds(WINDOW_SIZE_SECONDS))){
            clientCount.put(addr, 0);
            clientTimes.put(addr, LocalDateTime.now());
        }
        Integer count = clientCount.merge(addr, 1, Integer::sum);
        if (count > MAX_REQUEST_PER_MINUTE){
            throw new RuntimeException("访问过于频繁");
        }
        return true;
    }
}
